from flask import Blueprint, request, jsonify, g
from ..models import Admin, db
from datetime import datetime
import jwt
from ..config import Config
import traceback
from bson import ObjectId
from ..database import mongo_collection
import json

announcement_bp = Blueprint('announcement', __name__)
user_announcement_bp = Blueprint('user_announcement', __name__)  # 创建用户公告蓝图

# 辅助函数：验证管理员权限
def authenticate_admin():
    """验证管理员权限并返回管理员信息"""
    admin_id = request.headers.get('adminID')
    if not admin_id:
        return None, jsonify(code=40100, message="未授权，请先登录"), 401
    
    try:
        # 直接从数据库获取管理员信息
        admin = Admin.query.get(int(admin_id))
        if not admin or not admin.is_active:
            return None, jsonify(code=40100, message="管理员账号不存在或已被禁用"), 401
        
        return admin, None, None
    except Exception as e:
        return None, jsonify(code=50000, message="系统错误", error=str(e)), 500

# 辅助函数：ObjectId的JSON序列化
class JSONEncoder(json.JSONEncoder):
    def default(self, o):
        if isinstance(o, ObjectId):
            return str(o)
        if isinstance(o, datetime):
            return o.strftime('%Y-%m-%d %H:%M:%S')
        return json.JSONEncoder.default(self, o)

# 辅助函数：获取自增ID
def get_next_sequence(collection_name):
    """获取指定集合的下一个自增ID"""
    # 确定实际集合名称
    actual_collection = collection_name
    if collection_name in Config.MONGODB_COLLECTIONS:
        actual_collection = Config.MONGODB_COLLECTIONS[collection_name]
    
    with mongo_collection(actual_collection) as target_collection:
        # 检查集合是否为空
        count = target_collection.count_documents({})
        
        with mongo_collection("counters") as counter_collection:
            # 如果集合为空，重置计数器为1
            if count == 0:
                counter = counter_collection.find_one_and_update(
                    {"_id": collection_name},
                    {"$set": {"seq": 1}},
                    upsert=True,
                    return_document=True
                )
            else:
                # 否则递增计数器
                counter = counter_collection.find_one_and_update(
                    {"_id": collection_name},
                    {"$inc": {"seq": 1}},
                    upsert=True,
                    return_document=True
                )
            
            # 如果没有找到最大ID，从1开始
            if not counter or "seq" not in counter:
                counter_collection.insert_one({"_id": collection_name, "seq": 1})
                return 1
                
            return counter["seq"]

@announcement_bp.route('/v1/announcements', methods=['POST'])
def create_announcement():
    """
    创建系统公告接口
    
    请求参数：
    {
        "title": "公告标题",
        "content": "公告内容",
        "start_at": "2023-07-01 00:00:00",  # 公告开始时间
        "end_at": "2023-07-31 23:59:59",    # 公告结束时间（可选）
        "is_active": true,                   # 是否激活（可选，默认为true）
        "priority": 0                        # 优先级（可选，默认为0）
    }
    
    返回格式：
    {
        "code": 0,
        "message": "创建公告成功",
        "data": {
            "announcement_id": 1,
            "title": "公告标题",
            ...
        }
    }
    """
    admin, error_response, status_code = authenticate_admin()
    if error_response:
        return error_response, status_code
    
    try:
        # 获取请求数据
        data = request.get_json()
        if not data:
            return jsonify(code=40000, message="请求数据为空"), 400
        
        # 验证必填字段
        required_fields = ['title', 'content', 'start_at']
        for field in required_fields:
            if field not in data or not data[field]:
                return jsonify(code=40001, message=f"缺少必填字段: {field}"), 400
        
        # 解析时间格式
        try:
            start_at = datetime.strptime(data['start_at'], "%Y-%m-%d %H:%M:%S")
            end_at = None
            if 'end_at' in data and data['end_at']:
                end_at = datetime.strptime(data['end_at'], "%Y-%m-%d %H:%M:%S")
                
                # 验证结束时间必须晚于开始时间
                if end_at <= start_at:
                    return jsonify(code=40002, message="结束时间必须晚于开始时间"), 400
        except ValueError:
            return jsonify(code=40003, message="时间格式错误，请使用 YYYY-MM-DD HH:MM:SS 格式"), 400
        
        # 手动查询最大公告ID
        with mongo_collection(Config.MONGODB_COLLECTIONS["announcements"]) as collection:
            # 计算总数
            total_announcements = collection.count_documents({})
            
            if total_announcements == 0:
                # 如果没有公告，从1开始
                announcement_id = 1
            else:
                # 查询最大公告ID并加1
                max_id_doc = collection.find_one(sort=[("announcement_id", -1)])
                announcement_id = max_id_doc["announcement_id"] + 1 if max_id_doc else 1
        
        # 创建公告对象
        announcement = {
            "announcement_id": announcement_id,  # 使用手动设置的ID
            "title": data['title'],
            "content": data['content'],
            "start_at": start_at,
            "end_at": end_at,
            "is_active": data.get('is_active', True),
            "priority": data.get('priority', 0),
            "admin_id": admin.admin_id,
            "admin_name": admin.admin_name,
            "create_at": datetime.now(),
            "update_at": datetime.now()
        }
        
        # 保存到数据库
        with mongo_collection(Config.MONGODB_COLLECTIONS["announcements"]) as collection:
            collection.insert_one(announcement)
        
        # 构建响应数据
        response_data = {
            "announcement_id": announcement_id,
            "title": announcement["title"],
            "content": announcement["content"],
            "start_at": announcement["start_at"].strftime("%Y-%m-%d %H:%M:%S"),
            "end_at": announcement["end_at"].strftime("%Y-%m-%d %H:%M:%S") if announcement["end_at"] else None,
            "is_active": announcement["is_active"],
            "priority": announcement["priority"],
            "create_at": announcement["create_at"].strftime("%Y-%m-%d %H:%M:%S"),
            "admin_id": announcement["admin_id"],
            "admin_name": announcement["admin_name"]
        }
        
        return jsonify(
            code=0,
            message="创建公告成功",
            data=response_data
        ), 201
        
    except Exception as e:
        print(f"[SYSTEM ERROR] 创建公告异常: {str(e)}")
        traceback.print_exc()
        
        return jsonify(
            code=50000,
            message="系统繁忙，请稍后重试",
            error=str(e)
        ), 500

@announcement_bp.route('/v1/announcements', methods=['GET'])
def get_announcements():
    """
    获取系统公告列表，支持分页
    请求示例：/api/admin/v1/announcements?size=10&page=1&is_active=true
    
    参数说明：
    - page: 页码，默认为1
    - size: 每页记录数，默认为10
    - is_active: 是否只显示激活的公告，可选值为true或false，默认不筛选
    
    返回格式：
    {
        "code": 0,
        "message": "获取公告列表成功",
        "data": {
            "total": 总公告数,
            "page": 当前页码,
            "size": 每页记录数,
            "total_pages": 总页数,
            "announcements": [公告列表]
        }
    }
    """
    # 验证管理员权限
    admin, error_response, status_code = authenticate_admin()
    if error_response:
        return error_response, status_code
    
    try:
        # 获取分页参数
        page = request.args.get('page', 1, type=int)
        size = request.args.get('size', 10, type=int)
        is_active_str = request.args.get('is_active')
        
        # 验证分页参数
        if page < 1 or size < 1:
            return jsonify(
                code=40010,
                message="页码和每页数量必须为正整数"
            ), 400
        
        # 构建查询条件
        query = {}
        if is_active_str:
            is_active = is_active_str.lower() == 'true'
            query["is_active"] = is_active
        
        # 查询公告数据
        with mongo_collection(Config.MONGODB_COLLECTIONS["announcements"]) as collection:
            # 查找所有唯一的announcement_id
            unique_ids = collection.distinct("announcement_id", query)
            
            # 对于每个唯一ID，获取最新的公告
            latest_announcements = []
            for ann_id in unique_ids:
                # 按创建时间降序排序，获取最新的一条
                latest = collection.find({"announcement_id": ann_id}).sort("create_at", -1).limit(1)
                for doc in latest:
                    latest_announcements.append(doc)
            
            # 根据优先级和创建时间排序
            latest_announcements.sort(key=lambda x: (-x.get("priority", 0), -x["create_at"].timestamp()))
            
            # 计算总数（唯一ID的数量）
            total_announcements = len(latest_announcements)
            
            # 计算总页数
            total_pages = (total_announcements + size - 1) // size if total_announcements > 0 else 0
            
            # 分页处理
            start_idx = (page - 1) * size
            end_idx = start_idx + size
            paged_announcements = latest_announcements[start_idx:end_idx] if start_idx < total_announcements else []
            
            # 转换为列表
            announcement_list = []
            for announcement in paged_announcements:
                announcement_data = {
                    "announcement_id": announcement["announcement_id"],
                    "title": announcement["title"],
                    "content": announcement["content"],
                    "start_at": announcement["start_at"].strftime("%Y-%m-%d %H:%M:%S"),
                    "end_at": announcement["end_at"].strftime("%Y-%m-%d %H:%M:%S") if announcement.get("end_at") else None,
                    "is_active": announcement["is_active"],
                    "priority": announcement["priority"],
                    "create_at": announcement["create_at"].strftime("%Y-%m-%d %H:%M:%S"),
                    "update_at": announcement["update_at"].strftime("%Y-%m-%d %H:%M:%S") if announcement.get("update_at") else None,
                    "admin_id": announcement.get("admin_id"),
                    "admin_name": announcement.get("admin_name")
                }
                announcement_list.append(announcement_data)
        
        # 构建响应数据
        response = {
            "code": 0,
            "message": "获取公告列表成功",
            "data": {
                "total": total_announcements,
                "page": page,
                "size": size,
                "total_pages": total_pages,
                "announcements": announcement_list
            }
        }
        
        return jsonify(response), 200
        
    except Exception as e:
        print(f"[SYSTEM ERROR] 获取公告列表异常: {str(e)}")
        traceback.print_exc()
        
        return jsonify(
            code=50000,
            message="系统繁忙，请稍后重试",
            error=str(e)
        ), 500

@announcement_bp.route('/v1/announcement/detail', methods=['GET'])
def get_announcement_detail():
    """
    获取系统公告详情
    请求示例：/api/admin/v1/announcement/detail?id=1
    
    返回格式：
    {
        "code": 0,
        "message": "获取公告详情成功",
        "data": {
            "announcement_id": 1,
            "title": "公告标题",
            ...
        }
    }
    """
    # 验证管理员权限
    admin, error_response, status_code = authenticate_admin()
    if error_response:
        return error_response, status_code
    
    try:
        # 获取公告ID
        announcement_id = request.args.get('id', type=int)
        if not announcement_id:
            return jsonify(
                code=40001,
                message="缺少必填参数: id"
            ), 400
            
        # 查询公告详情
        with mongo_collection(Config.MONGODB_COLLECTIONS["announcements"]) as collection:
            # 查找指定ID的最新公告
            announcements = collection.find({"announcement_id": announcement_id}).sort("create_at", -1).limit(1)
            announcement = None
            for doc in announcements:
                announcement = doc
                break
            
            if not announcement:
                return jsonify(
                    code=40400,
                    message="公告不存在"
                ), 404
            
            # 构建响应数据
            announcement_data = {
                "announcement_id": announcement["announcement_id"],
                "title": announcement["title"],
                "content": announcement["content"],
                "start_at": announcement["start_at"].strftime("%Y-%m-%d %H:%M:%S"),
                "end_at": announcement["end_at"].strftime("%Y-%m-%d %H:%M:%S") if announcement.get("end_at") else None,
                "is_active": announcement["is_active"],
                "priority": announcement["priority"],
                "create_at": announcement["create_at"].strftime("%Y-%m-%d %H:%M:%S"),
                "update_at": announcement["update_at"].strftime("%Y-%m-%d %H:%M:%S") if announcement.get("update_at") else None,
                "admin_id": announcement.get("admin_id"),
                "admin_name": announcement.get("admin_name")
            }
            
            return jsonify(
                code=0,
                message="获取公告详情成功",
                data=announcement_data
            ), 200
        
    except Exception as e:
        print(f"[SYSTEM ERROR] 获取公告详情异常: {str(e)}")
        traceback.print_exc()
        
        return jsonify(
            code=50000,
            message="系统繁忙，请稍后重试",
            error=str(e)
        ), 500

@announcement_bp.route('/v1/announcements/update', methods=['POST'])
def update_announcement():
    """
    更新系统公告
    请求示例：/api/admin/v1/announcements/update
    
    请求参数：
    {
        "ori_announcements_id": 1,          # 公告ID
        "title": "更新后的公告标题",
        "content": "更新后的公告内容",
        "start_at": "2023-07-01 00:00:00",  # 公告开始时间
        "end_at": "2023-07-31 23:59:59",    # 公告结束时间（可选）
        "is_active": true,                   # 是否激活（可选）
        "priority": 0                        # 优先级（可选）
    }
    
    返回格式：
    {
        "code": 0,
        "message": "更新公告成功",
        "data": {
            "announcement_id": 1,
            "title": "更新后的公告标题",
            ...
        }
    }
    """
    # 验证管理员权限
    admin, error_response, status_code = authenticate_admin()
    if error_response:
        return error_response, status_code
    
    try:
        # 获取请求数据
        data = request.get_json()
        if not data:
            return jsonify(code=40000, message="请求数据为空"), 400
        
        # 获取公告ID
        announcement_id = data.get('ori_announcements_id')
        if not announcement_id:
            return jsonify(
                code=40001,
                message="缺少必填参数: ori_announcements_id"
            ), 400
            
        # 确保announcement_id是整数类型
        try:
            announcement_id = int(announcement_id)
        except (ValueError, TypeError):
            return jsonify(
                code=40001,
                message="公告ID必须是整数"
            ), 400
        
        # 添加调试日志
        print(f"[DEBUG] 尝试更新公告ID: {announcement_id}")
            
        # 查询公告是否存在
        with mongo_collection(Config.MONGODB_COLLECTIONS["announcements"]) as collection:
            # 直接查找公告记录，如果不存在则返回404
            announcement = collection.find_one(
                {"announcement_id": announcement_id},
                sort=[("create_at", -1)]
            )
            
            print(f"[DEBUG] 查找到的公告记录: {announcement is not None}")
            if announcement:
                print(f"[DEBUG] 公告详情: ID={announcement.get('announcement_id')}, Title={announcement.get('title')}")
            else:
                print(f"[DEBUG] 公告ID {announcement_id} 不存在，返回404错误")
                return jsonify(
                    code=40400,
                    message="公告不存在"
                ), 404
            
            # 创建新公告数据
            new_announcement = {
                "announcement_id": announcement_id,  # 保持相同的ID
                "update_at": datetime.now(),
                "admin_id": admin.admin_id,
                "admin_name": admin.admin_name,
                "create_at": datetime.now()  # 新文档的创建时间
            }
            
            # 从原公告复制未更新的字段
            for field in ["title", "content", "start_at", "end_at", "is_active", "priority"]:
                if field in data and data[field] is not None:
                    # 处理日期字段
                    if field in ["start_at", "end_at"] and data[field]:
                        try:
                            new_announcement[field] = datetime.strptime(data[field], "%Y-%m-%d %H:%M:%S")
                        except ValueError:
                            return jsonify(code=40003, message=f"{field}格式错误，请使用 YYYY-MM-DD HH:MM:SS 格式"), 400
                    else:
                        new_announcement[field] = data[field]
                else:
                    # 如果请求中没有提供该字段，则从原公告中复制
                    new_announcement[field] = announcement[field]
            
            # 验证开始和结束时间
            if new_announcement.get("end_at") and new_announcement["start_at"] >= new_announcement["end_at"]:
                return jsonify(code=40002, message="结束时间必须晚于开始时间"), 400
            
            # 插入新的公告记录
            print(f"[DEBUG] 即将插入新的公告记录，ID: {announcement_id}")
            result = collection.insert_one(new_announcement)
            print(f"[DEBUG] 插入结果: {result.inserted_id}")
            
            # 构建响应数据
            announcement_data = {
                "announcement_id": new_announcement["announcement_id"],
                "title": new_announcement["title"],
                "content": new_announcement["content"],
                "start_at": new_announcement["start_at"].strftime("%Y-%m-%d %H:%M:%S"),
                "end_at": new_announcement["end_at"].strftime("%Y-%m-%d %H:%M:%S") if new_announcement.get("end_at") else None,
                "is_active": new_announcement["is_active"],
                "priority": new_announcement["priority"],
                "create_at": new_announcement["create_at"].strftime("%Y-%m-%d %H:%M:%S"),
                "update_at": new_announcement["update_at"].strftime("%Y-%m-%d %H:%M:%S") if new_announcement.get("update_at") else None,
                "admin_id": new_announcement.get("admin_id"),
                "admin_name": new_announcement.get("admin_name")
            }
            
            print(f"[DEBUG] 公告更新成功，返回数据")
            # 返回更新成功消息
            return jsonify(
                code=0,
                message="更新公告成功",
                data=announcement_data
            ), 200
        
    except Exception as e:
        print(f"[SYSTEM ERROR] 更新公告异常: {str(e)}")
        traceback.print_exc()
        
        return jsonify(
            code=50000,
            message="系统繁忙，请稍后重试",
            error=str(e)
        ), 500

@announcement_bp.route('/v1/announcements/delete', methods=['DELETE'])
def delete_announcement():
    """
    删除系统公告
    请求示例：/api/admin/v1/announcements/delete?id=1
    
    返回格式：
    {
        "code": 0,
        "message": "删除公告成功"
    }
    """
    # 验证管理员权限
    admin, error_response, status_code = authenticate_admin()
    if error_response:
        return error_response, status_code
    
    try:
        # 获取公告ID
        announcement_id = request.args.get('id', type=int)
        if not announcement_id:
            return jsonify(
                code=40001,
                message="缺少必填参数: id"
            ), 400
            
        # 查询公告是否存在并删除
        with mongo_collection(Config.MONGODB_COLLECTIONS["announcements"]) as collection:
            announcement = collection.find_one({"announcement_id": announcement_id})
            
            if not announcement:
                return jsonify(
                    code=40400,
                    message="公告不存在"
                ), 404
            
            # 执行删除
            collection.delete_one({"announcement_id": announcement_id})
            
            return jsonify(
                code=0,
                message="删除公告成功"
            ), 200
        
    except Exception as e:
        print(f"[SYSTEM ERROR] 删除公告异常: {str(e)}")
        traceback.print_exc()
        
        return jsonify(
            code=50000,
            message="系统繁忙，请稍后重试",
            error=str(e)
        ), 500

@user_announcement_bp.route('/v1/user/announcements/read', methods=['POST'])
def mark_announcement_read():
    """
    用户标记公告已读接口
    
    请求参数：
    {
        "user_id": 123,
        "announcement_id": 1
    }
    
    返回格式：
    {
        "code": 0,
        "message": "标记已读成功",
        "data": {
            "user_id": 用户ID,
            "announcement_id": int(公告ID),
            "read_at": "阅读时间"
        }
    }
    """
    try:
        # 获取请求数据
        data = request.get_json()
        if not data:
            return jsonify(code=40000, message="请求数据为空"), 400
        
        # 验证必填字段
        user_id = data.get('user_id')
        announcement_id = data.get('announcement_id')
        
        if not user_id:
            return jsonify(code=40001, message="缺少必填字段: user_id"), 400
        if not announcement_id:
            return jsonify(code=40001, message="缺少必填字段: announcement_id"), 400
        
        # 验证数据类型
        try:
            user_id = int(user_id)
            announcement_id = int(announcement_id)
        except (ValueError, TypeError):
            return jsonify(code=40001, message="用户ID和公告ID必须是整数"), 400
        
        # 验证用户ID格式
        from ..utils import validate_user_id
        if not validate_user_id(user_id):
            return jsonify(code=40007, message="无效的用户ID格式"), 400
        
        # 验证公告是否存在且激活
        with mongo_collection(Config.MONGODB_COLLECTIONS["announcements"]) as collection:
            announcement = collection.find_one(
                {"announcement_id": announcement_id, "is_active": True},
                sort=[("create_at", -1)]
            )
            
            if not announcement:
                return jsonify(code=40404, message="公告不存在或未激活"), 404
            
            # 检查公告是否在有效期内
            current_time = datetime.now()
            if announcement["start_at"] > current_time:
                return jsonify(code=40005, message="公告尚未开始"), 400
            
            if announcement.get("end_at") and announcement["end_at"] < current_time:
                return jsonify(code=40006, message="公告已过期"), 400
        
        # 检查用户是否已经标记过该公告
        with mongo_collection(Config.MONGODB_COLLECTIONS.get("user_announcement_reads", "user_announcement_reads")) as read_collection:
            existing_read = read_collection.find_one({
                "user_id": user_id,
                "announcement_id": announcement_id
            })
            
            if existing_read:
                return jsonify(
                    code=0,
                    message="该公告已标记为已读",
                    data={
                        "user_id": user_id,
                        "announcement_id": announcement_id,
                        "read_at": existing_read["read_at"].strftime("%Y-%m-%d %H:%M:%S")
                    }
                ), 200
            
            # 创建阅读记录
            read_record = {
                "user_id": user_id,
                "announcement_id": announcement_id,
                "read_at": datetime.now(),
                "create_at": datetime.now()
            }
            
            read_collection.insert_one(read_record)
        
        # 构建响应数据
        response_data = {
            "user_id": user_id,
            "announcement_id": announcement_id,
            "read_at": read_record["read_at"].strftime("%Y-%m-%d %H:%M:%S")
        }
        
        return jsonify(
            code=0,
            message="标记已读成功",
            data=response_data
        ), 201
        
    except Exception as e:
        print(f"[SYSTEM ERROR] 标记公告已读异常: {str(e)}")
        traceback.print_exc()
        
        return jsonify(
            code=50000,
            message="系统繁忙，请稍后重试",
            error=str(e)
        ), 500

@user_announcement_bp.route('/v1/user/announcements', methods=['GET'])
def get_user_unread_announcements():
    """
    用户获取未读公告列表，支持分页
    请求示例：/api/v1/user/announcements?user_id=123&size=10&page=1
    
    参数说明：
    - user_id: 用户ID（必填）
    - page: 页码，默认为1
    - size: 每页记录数，默认为10
    
    返回格式：
    {
        "code": 0,
        "message": "获取未读公告列表成功",
        "data": {
            "total": 总公告数,
            "page": 当前页码,
            "size": 每页记录数,
            "total_pages": 总页数,
            "announcements": [未读公告列表]
        }
    }
    """
    try:
        # 获取请求参数
        user_id = request.args.get('user_id')
        page = request.args.get('page', 1, type=int)
        size = request.args.get('size', 10, type=int)
        
        # 验证必填参数
        if not user_id:
            return jsonify(code=40001, message="缺少必填参数: user_id"), 400
        
        # 验证用户ID格式
        try:
            user_id = int(user_id)
        except (ValueError, TypeError):
            return jsonify(code=40001, message="用户ID必须是整数"), 400
        
        from ..utils import validate_user_id
        if not validate_user_id(user_id):
            return jsonify(code=40007, message="无效的用户ID格式"), 400
        
        # 验证分页参数
        if page < 1 or size < 1:
            return jsonify(
                code=40010,
                message="页码和每页数量必须为正整数"
            ), 400
        
        current_time = datetime.now()
        
        # 获取用户已读的公告ID列表
        with mongo_collection(Config.MONGODB_COLLECTIONS.get("user_announcement_reads", "user_announcement_reads")) as read_collection:
            read_announcement_ids = [
                doc["announcement_id"] 
                for doc in read_collection.find({"user_id": user_id}, {"announcement_id": 1})
            ]
        
        # 构建查询条件：激活且在有效期内的公告
        query = {
            "is_active": True,
            "start_at": {"$lte": current_time}
        }
        
        # 添加结束时间条件（如果设置了结束时间）
        query["$or"] = [
            {"end_at": {"$exists": False}},
            {"end_at": None},
            {"end_at": {"$gte": current_time}}
        ]
        
        # 查询公告数据
        with mongo_collection(Config.MONGODB_COLLECTIONS["announcements"]) as collection:
            # 获取所有有效的公告记录
            all_announcements = list(collection.find(query).sort("create_at", -1))
            
            # 创建一个字典来存储每个announcement_id的最新记录
            latest_announcements = {}
            for doc in all_announcements:
                ann_id = doc["announcement_id"]
                # 只保留每个announcement_id的最新记录
                if ann_id not in latest_announcements:
                    latest_announcements[ann_id] = doc
            
            # 过滤掉已读的公告
            unread_announcements = [
                doc for ann_id, doc in latest_announcements.items() 
                if ann_id not in read_announcement_ids
            ]
            
            # 根据优先级和创建时间排序
            unread_announcements.sort(key=lambda x: (-x.get("priority", 0), -x["create_at"].timestamp()))
            
            # 计算总数
            total_announcements = len(unread_announcements)
            
            # 计算总页数
            total_pages = (total_announcements + size - 1) // size if total_announcements > 0 else 0
            
            # 分页处理
            start_idx = (page - 1) * size
            end_idx = start_idx + size
            paged_announcements = unread_announcements[start_idx:end_idx] if start_idx < total_announcements else []
            
            # 转换为列表
            announcement_list = []
            for announcement in paged_announcements:
                # 确保返回的是数字类型的announcement_id而不是MongoDB的ObjectId
                announcement_data = {
                    "announcement_id": announcement["announcement_id"],
                    "title": announcement["title"],
                    "content": announcement["content"],
                    "start_at": announcement["start_at"].strftime("%Y-%m-%d %H:%M:%S"),
                    "end_at": announcement["end_at"].strftime("%Y-%m-%d %H:%M:%S") if announcement.get("end_at") else None,
                    "priority": announcement.get("priority", 0),
                    "create_at": announcement["create_at"].strftime("%Y-%m-%d %H:%M:%S"),
                    "admin_name": announcement.get("admin_name")
                }
                announcement_list.append(announcement_data)
        
        # 构建响应数据
        response = {
            "code": 0,
            "message": "获取未读公告列表成功",
            "data": {
                "total": total_announcements,
                "page": page,
                "size": size,
                "total_pages": total_pages,
                "announcements": announcement_list
            }
        }
        
        return jsonify(response), 200
        
    except Exception as e:
        print(f"[SYSTEM ERROR] 获取未读公告列表异常: {str(e)}")
        traceback.print_exc()
        
        return jsonify(
            code=50000,
            message="系统繁忙，请稍后重试",
            error=str(e)
        ), 500 